package com.bowos.utils;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

public class RenderUtils {
	//header 常量定义
		private static final String ENCODING_PREFIX = "encoding:";
		private static final String NOCACHE_PREFIX = "no-cache:";
		private static final String ENCODING_DEFAULT = "UTF-8";
		private static final boolean NOCACHE_DEFAULT = true;
		
		private static Logger logger = LoggerFactory.getLogger(RenderUtils.class);
		
		/**
		 * 直接输出内容的简便函数.
		 
		 * eg.
		 * render("text/plain", "hello", "encoding:GBK");
		 * render("text/plain", "hello", "no-cache:false");
		 * render("text/plain", "hello", "encoding:GBK", "no-cache:false");
		 * 
		 * @param headers 可变的header数组，目前接受的值为"encoding:""no-cache:",默认值分别为UTF-8和true.                 
		 */
		private static void render(final HttpServletResponse response, final String contentType, final String content, final String... headers) {
			try {
				//分析headers参数
				String encoding = ENCODING_DEFAULT;
				boolean noCache = NOCACHE_DEFAULT;
				for (String header : headers) {
					String headerName = StringUtils.substringBefore(header, ":");
					String headerValue = StringUtils.substringAfter(header, ":");

					if (StringUtils.equalsIgnoreCase(headerName, ENCODING_PREFIX)) {
						encoding = headerValue;
					} else if (StringUtils.equalsIgnoreCase(headerName, NOCACHE_PREFIX)) {
						noCache = Boolean.parseBoolean(headerValue);
					} else
						throw new IllegalArgumentException(headerName + "不是一个合法的header类型");
				}

				//设置headers参数
				String fullContentType = contentType + ";charset=" + encoding;
				response.setContentType(fullContentType);
				if (noCache) {
					response.setHeader("Pragma", "No-cache");
					response.setHeader("Cache-Control", "no-cache");
					response.setDateHeader("Expires", 0);
				}

				response.getWriter().write(content);

			} catch (IOException e) {
				logger.error(e.getMessage(), e);
			}
		}
		
		/**
		 * 直接输出文本.
		 * @see #render(String, String, String...)
		 */
		public static void renderText(final HttpServletResponse response, final String text, final String... headers) {
			render(response, "text/plain", text, headers);
		}

		/**
		 * 直接输出HTML.
		 * @see #render(String, String, String...)
		 */
		public static void renderHtml(final HttpServletResponse response, final String html, final String... headers) {
			render(response, "text/html", html, headers);
		}

		/**
		 * 直接输出XML.
		 * @see #render(String, String, String...)
		 */
		public static void renderXml(final HttpServletResponse response, final String xml, final String... headers) {
			render(response, "text/xml", xml, headers);
		}

		/**
		 * 直接输出JSON.
		 * 
		 * @param string json字符�?
		 * @see #render(String, String, String...)
		 */
		public static void renderJson(final HttpServletResponse response, final String string, final String... headers) {
			render(response, "application/json", string, headers);
		}
		
		/**
		 * 直接输出javascript
		 */
		public static void renderJavascript(final HttpServletResponse response, final String string, final String... headers) {
			render(response, "text/javascript", string, headers);
		}

		/**
		 * 直接输出JSON.
		 * 
		 * @param map Map对象,将被转化为json字符�?.
		 * @see #render(String, String, String...)
		 */
		public static void renderJson(final HttpServletResponse response, final Map<?, ?> map, final String... headers) {
			String jsonString = new JSONObject(map).toString();
			renderJson(response, jsonString, headers);
		}

		/**
		 * 直接输出JSON.
		 * 
		 * @param object Java对象,将被转化为json字符�?.
		 * @see #render(String, String, String...)
		 */
		public static void renderJson(final HttpServletResponse response, final Object object, final String... headers) {
			String jsonString = new JSONObject(object).toString();
			renderJson(response, jsonString, headers);
		}
		
		/**
		 * 直接输出Image
		 * @param image
		 * @throws IOException 
		 */
		public static void renderImage(final HttpServletResponse response, final BufferedImage image) throws IOException{
			response.setContentType("image/gif");
			response.setHeader("Pragma", "No-cache");
			response.setHeader("Cache-Control", "no-cache");
			response.setDateHeader("Expires", 0);
			
			ServletOutputStream out = response.getOutputStream();
			JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
			encoder.encode(image);
			out.flush();
			out.close();
		}
}
